package lastSymbol

import (
	"fmt"
	"log"
	"strconv"
	"strings"
	"time"

	"github.com/Jeffail/gabs"
	kjson "github.com/heyuanlong/go-tools/json"
	"github.com/parnurzeal/gorequest"
)

type BinancePrice struct {
	httpDomain string
}

func NewBinancePriceStruct() *BinancePrice {
	obj := &BinancePrice{}
	obj.init()
	return obj
}

func (ts *BinancePrice) init() {
	ts.httpDomain = "https://api.binance.com/"
}

func (ts *BinancePrice) GetPriceUsdt(name string) (float64, error) {
	symbol := strings.ToUpper(name) + "USDT"
	uri := ts.httpDomain + "api/v3/ticker/price?symbol=" + symbol
	request := gorequest.New().Timeout(time.Duration(2) * time.Second)
	_, body, errs := request.Get(uri).End()
	if errs != nil {
		log.Println(errs)
		return 0, errs[0]
	}

	jsonParsed, err := gabs.ParseJSON([]byte(body))
	if err != nil {
		err = fmt.Errorf("get ok lasted price failed, err:%v\n", err.Error())
		return 0, err
	}
	s, err := kjson.GabsGetJsonString(jsonParsed, "price")
	if err != nil {
		log.Println(body, err)
		return 0, err
	}

	retv, errx := strconv.ParseFloat(s, 64)
	return retv, errx
}

func (ts *BinancePrice) GetPriceRmb(name string) (float64, error) {
	return 0, nil
}
